package com.xuwangcheng.springboot.common.base.entity;

import com.xuwangcheng.springboot.common.exception.AppErrorCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

/**
 * 返回模型
 * @author xuwangcheng
 * @version 1.0.0
 * @description
 * @date 2020/4/28 17:23
 */
@ApiModel(value = "响应结果")
public class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "为0表示成功，其他表示失败")
    private int code = 0;
    @ApiModelProperty(value = "返回消息")
    private String msg = "ok";
    @ApiModelProperty(value = "返回数据")
    private T data;

    public Result<T> ok(T data) {
        this.setData(data);
        return this;
    }

    public boolean success() {
        return code == 0 ? true : false;
    }

    public Result<T> error() {
        this.code = AppErrorCode.SERVER_ERROR.getCode();
        this.msg = AppErrorCode.SERVER_ERROR.getMsg();
        return this;
    }

    public Result<T> error(int code) {
        this.code = code;
        this.msg = AppErrorCode.getByCode(code).getMsg();
        return this;
    }

    public Result<T> error(int code, String msg) {
        this.code = code;
        this.msg = msg;
        return this;
    }

    public Result<T> error(String msg) {
        this.code = AppErrorCode.SERVER_ERROR.getCode();
        this.msg = msg;
        return this;
    }

    public Result<T> error(AppErrorCode code) {
        this.code = code.getCode();
        this.msg = code.getMsg();
        return this;
    }

    public Result<T> data(T data) {
        this.setData(data);
        return this;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

}
